
#include "LoadingWnd.h"
#include "ui/CocosGUI.h"
#include "Event.h"
#include "EventMgr.h"
#include "Enum.h"

USING_NS_CC;
using namespace ui;

LoadingWnd::LoadingWnd()

{
}

LoadingWnd::~LoadingWnd()
{
}

Scene* LoadingWnd::createScene()
{
    auto scene = Scene::create();
    auto layer = LoadingWnd::create();
    scene->addChild(layer);
    return scene;
}

bool LoadingWnd::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

	schedule(schedule_selector(LoadingWnd::logic));
    return true;
}

ProgressTimer * LoadingWnd::addProgress(const char *bgPngName,const char *barPngName)
{
	if (bgPngName == nullptr || barPngName == nullptr) return nullptr;

    Size size = Director::getInstance()->getWinSize();
	auto progressBarBg = Sprite::create(bgPngName);
    progressBarBg->setPosition(Point(size.width / 2,  size.height / 2 ));
    addChild(progressBarBg);
	progressBar = ProgressTimer::create(Sprite::create(barPngName));
    progressBar ->setType(ProgressTimer::Type::BAR);
    progressBar ->setMidpoint(Point(0,0.5f));
    progressBar ->setBarChangeRate(Point(1,0));
    progressBar->setPercentage(0);
    progressBar->setAnchorPoint(Point(0.5f, 0.5f));
    progressBar->setPosition(Point(progressBarBg->getContentSize().width / 2,  progressBarBg->getContentSize().height /6 ));
    progressBarBg->addChild(progressBar);
    return progressBar;
    
}
void LoadingWnd::logic(float dt)
{
    float percent = (float)numberOfLoadedRes / (float)totalNumOfRes * 100;
    
    progressBar->setPercentage(percent);
    
    if (numberOfLoadedRes==totalNumOfRes) 
	{
		UIEventMsg eventMsg;
		eventMsg._msgCmd = LOAD_FINISH;
		Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(EVENT_LOAD_FINISH, &eventMsg);
    }
}

void LoadingWnd::loadFileResources(std::vector<std::string> &vecPlistName)
{
	for (int i = 0; i < (int)vecPlistName.size(); ++i)
	{
		SpriteFrameCache::getInstance()->addSpriteFramesWithFile(vecPlistName[i]);
		numberOfLoadedRes++;
	}
}

void LoadingWnd::loadPngResources(std::vector<std::string> &vecPngName)
{
	for (int i = 0; i < (int)vecPngName.size(); ++i)
	{
		Director::getInstance()->getTextureCache()->addImageAsync(vecPngName[i], CC_CALLBACK_1(LoadingWnd::loadPngCallBack, this));
		numberOfLoadedRes++;
	}
}

void LoadingWnd::loadPngCallBack(cocos2d::Texture2D *texture)
{
    numberOfLoadedRes++;
}


